package com.lfg.leetcode.leetcode200;

import java.util.ArrayList;
import java.util.List;

public class No210findOrder {

    public static void main(String[] args) {
//        int[] ret = findOrder(4, new int[][]{
//                new int[]{1, 0},
//                new int[]{2, 0},
//                new int[]{3, 1},
//                new int[]{3, 2}
//        });
        int[] ret = findOrder(2, new int[][]{new int[]{1, 0}});
        for (int i : ret) {
            System.out.println(i);
        }
    }


    public static int[] findOrder(int numCourses, int[][] prerequisites) {
        List<Integer> ret = new ArrayList<>(numCourses);
        int[] inDegree = new int[numCourses];
        List<List<Integer>> data = new ArrayList<>(numCourses);
        for (int i = 0; i < numCourses; i++) {
            data.add(new ArrayList<>(numCourses));
        }
        for (int i = 0; i < prerequisites.length; i++) {
            inDegree[prerequisites[i][1]]++;
            data.get(prerequisites[i][0]).add(prerequisites[i][1]);
        }
        List<Integer> root = new ArrayList<>(numCourses);
        for (int i = 0; i < numCourses; i++) {
            if (inDegree[i] == 0) {
                root.add(i);
            }
        }
        for (int i : root) {
            if (inDegree[i] != 0) {
                continue;
            }
            ret.add(i);
            if (!canFinish(i, inDegree, data, ret)) {
                return new int[]{};
            }
        }
        for (int i = 0; i < numCourses; i++) {
            if (inDegree[i] != 0) {
                return new int[]{};
            }
        }
        int index = 0;
        for (int i = ret.size() - 1; i >= 0; i--) {
            inDegree[index++] = ret.get(i);
        }
        return inDegree;
    }

    public static boolean canFinish(int i, int[] inDegree, List<List<Integer>> data, List<Integer> ret) {
        List<Integer> list = data.get(i);
        for (int n : list) {
            if (0 != --inDegree[n]) {
                continue;
            }
            ret.add(n);
            if (!canFinish(n, inDegree, data, ret)) {
                return false;
            }
        }
        return true;
    }
}
